package com.lxl.bt.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectChangeListener;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.IFillFormatter;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.dataprovider.LineDataProvider;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.github.mikephil.charting.utils.MPPointF;
import com.lxl.bt.Constant;
import com.lxl.bt.R;
import com.lxl.bt.activity.BaseFragment;
import com.lxl.bt.activity.ProductListActivity;
import com.lxl.bt.bean.A_Login;
import com.lxl.bt.bean.Inbean;
import com.lxl.bt.bean.OutBean;
import com.lxl.bt.bean.RecordBean;
import com.lxl.bt.bean.WakuangBean;
import com.lxl.bt.net.NetApi;
import com.lxl.bt.net.Result;
import com.lxl.bt.retorfit.NetCallback;
import com.lxl.bt.retorfit.RetrofitUtil;
import com.lxl.bt.util.ACache;
import com.yanzhenjie.sofia.Sofia;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Create by lvxinlong
 * on 我的
 * on 2020年12月5日10:42:43
 **/
public class WaKuangFragment extends BaseFragment implements OnChartValueSelectedListener {


    @BindView(R.id.ivBack)
    ImageView ivBack;
    @BindView(R.id.rlBack)
    RelativeLayout rlBack;
    @BindView(R.id.txt_toolbar_title)
    TextView txtToolbarTitle;
    @BindView(R.id.ivRight)
    ImageView ivRight;
    @BindView(R.id.tvRight)
    TextView tvRight;
    @BindView(R.id.rlRight)
    RelativeLayout rlRight;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.ll1_1)
    LinearLayout ll11;
    @BindView(R.id.ll1_2)
    LinearLayout ll12;
    @BindView(R.id.ll2_1)
    LinearLayout ll21;
    @BindView(R.id.ll2_2)
    LinearLayout ll22;
    @BindView(R.id.tvShow)
    TextView tvShow;
    @BindView(R.id.ivShow)
    ImageView ivShow;
    @BindView(R.id.ivJiSuan)
    ImageView ivJiSuan;
    @BindView(R.id.tvTotalcc)
    TextView tvTotalcc;
    @BindView(R.id.tvDcc)
    TextView tvDcc;
    @BindView(R.id.chart)
    LineChart chart;
    @BindView(R.id.piechart1)
    PieChart piechart1;
    @BindView(R.id.ll3_1)
    LinearLayout ll31;
    @BindView(R.id.piechart2)
    PieChart piechart2;
    @BindView(R.id.ll3_2)
    LinearLayout ll32;
    @BindView(R.id.tvCommit)
    TextView tvCommit;
    @BindView(R.id.tvqwsl)
    TextView tvqwsl;
    @BindView(R.id.tvslnd)
    TextView tvslnd;
    @BindView(R.id.tvdqbj)
    TextView tvdqbj;
    @BindView(R.id.tvmtcc)
    TextView tvmtcc;
    @BindView(R.id.tvInRmb)
    TextView tvInRmb;
    @BindView(R.id.tvInUsdt)
    TextView tvInUsdt;
    @BindView(R.id.tvInBtc)
    TextView tvInBtc;
    @BindView(R.id.tvOutsl)
    TextView tvOutsl;
    @BindView(R.id.tvOutkj)
    TextView tvOutkj;
    @BindView(R.id.tvyesday)
    TextView tvyesday;

    @BindView(R.id.tv_product_per_day)
    TextView tvProductPerDay;

    @BindView(R.id.tv_total_product)
    TextView tvTotalProduct;
    @BindView(R.id.tv_will_product)
    TextView tvWillProduct;
    @BindView(R.id.tv_currency)
    TextView tvCurrency;
    @BindView(R.id.tv_currency_calculate)
    TextView tvCurrencyCalculate;
    @BindView(R.id.tv_currency_machine)
    TextView tvCurrencyMachine;


    private Unbinder unbinder;
    ACache aCache;
    A_Login a_login;
    int index = 0;
    private String[] reqs = {"btc", "eth", "fil"};
    boolean showValue = true;
    WakuangBean wakuangbean;

    public static WaKuangFragment newInstance() {
        Bundle bundle = new Bundle();
        WaKuangFragment fragment = new WaKuangFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_wakuang, container, false);
//        ((BaseActivity) getActivity()).setStatusBarFullTransparent();
        //返回一个Unbinder值（进行解绑），注意这里的this不能使用getActivity()
        unbinder = ButterKnife.bind(this, view);
//        EventBus.getDefault().register(this);
        Sofia.with(getActivity()).statusBarBackgroundAlpha(0)
                .invasionStatusBar();
//                .statusBarLightFont();
//                .statusBarDarkFont();

        //rlBack.setVisibility(View.VISIBLE);
        tvRight.setText("币种");
        rlRight.setVisibility(View.VISIBLE);
        txtToolbarTitle.setText("BTC挖矿数据");
        initChart();
        initPieChart(piechart1);
        initPieChart(piechart2);
        setData(piechart1, 2, 60);
        setData(piechart2, 1, 60);

        return view;
    }

    //饼状图
    private void initPieChart(PieChart chart) {
        chart.setCenterTextSize(10);
        chart.setUsePercentValues(false);
        chart.getDescription().setEnabled(false);
        chart.setExtraOffsets(5, 10, 5, 5);

        chart.setDragDecelerationFrictionCoef(0.95f);
//        chart.setCenterText(generateCenterSpannableText());
        chart.setDrawHoleEnabled(true);
        chart.setHoleColor(getResources().getColor(R.color.c1E1D1D));

        chart.setTransparentCircleColor(Color.WHITE);
        chart.setTransparentCircleAlpha(110);

        chart.setDrawSlicesUnderHole(false);
        chart.setHoleRadius(90f);
        chart.setTransparentCircleRadius(91f);

        chart.setDrawCenterText(true);
        chart.setDrawEntryLabels(false);
        chart.setUsePercentValues(false);
        chart.setRotationAngle(0);
        // enable rotation of the chart by touch
        chart.setRotationEnabled(false);
        chart.setHighlightPerTapEnabled(false);

        // chart.setUnit(" €");
        // chart.setDrawUnitsInChart(true);

        // add a selection listener
        chart.setOnChartValueSelectedListener(this);

        chart.setDrawEntryLabels(false);

        chart.animateY(1400, Easing.EaseInOutQuad);
        // chart.spin(2000, 0, 360);

        Legend l = chart.getLegend();
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
        l.setOrientation(Legend.LegendOrientation.VERTICAL);
        l.setDrawInside(false);
        l.setXEntrySpace(7f);
        l.setYEntrySpace(0f);
        l.setYOffset(0f);
        l.setEnabled(false);

        // entry label styling
//        chart.setEntryLabelColor(Color.WHITE);
//        chart.setEntryLabelTextSize(12f);

    }

    private SpannableString generateCenterSpannableText(String ss) {

        SpannableString s = new SpannableString(ss);
        s.setSpan(new ForegroundColorSpan(Color.WHITE), 0, s.length(), 0);
        return s;
    }

    //曲线图
    private void initChart() {
        chart.setViewPortOffsets(0, 0, 0, 0);
//        chart.setBackgroundColor(Color.rgb(104, 241, 175));
        chart.setBackgroundColor(getResources().getColor(R.color.c1E1D1D));
        // no description text
        chart.getDescription().setEnabled(false);

        // enable touch gestures
        chart.setTouchEnabled(true);

        // enable scaling and dragging
        chart.setDragEnabled(true);
        chart.setScaleEnabled(true);

        // if disabled, scaling can be done on x- and y-axis separately
        chart.setPinchZoom(false);

        chart.setDrawGridBackground(false);
        chart.setMaxHighlightDistance(300);

        XAxis x = chart.getXAxis();
        x.setEnabled(false);

        YAxis y = chart.getAxisLeft();
        y.setLabelCount(6, false);
        y.setTextColor(R.color.CEAD79);
        y.setPosition(YAxis.YAxisLabelPosition.INSIDE_CHART);
        y.setDrawGridLines(false);
        y.setAxisLineColor(R.color.CEAD79);

        chart.getAxisRight().setEnabled(false);
        chart.getLegend().setEnabled(false);
        chart.animateXY(2000, 2000);

        chart.invalidate();
    }

    //曲线图数据填充
    private void setData(RecordBean record) {
        //设置币种
        String req = reqs[index].toUpperCase();
        tvProductPerDay.setText("每日每T产出(currency)".replace("currency",req));
        //tvTotalProduct.setText("累计产出(currency)".replace("currency",req));
        //tvWillProduct.setText("预计待产出(currency)".replace("currency",req));
        //tvCurrency.setText(req);
        tvCurrencyCalculate.setText("currency云运算".replace("currency",req));
        tvCurrencyMachine.setText("currency矿机".replace("currency",req));

        List<RecordBean.RecordContentBean> beans=record.content;
        ArrayList<Entry> values = new ArrayList<>();
        for (int i = 0; i < beans.size(); i++) {
//            float val = (float) (Math.random() * (range + 1)) + 20;
            values.add(new Entry(i, Float.valueOf(beans.get(i).amount)));
        }

        LineDataSet set1;

        if (chart.getData() != null &&
                chart.getData().getDataSetCount() > 0) {
            set1 = (LineDataSet) chart.getData().getDataSetByIndex(0);
            set1.setValues(values);
            chart.getData().notifyDataChanged();
            chart.notifyDataSetChanged();
        } else {
            // create a dataset and give it a type
            set1 = new LineDataSet(values, "DataSet 1");

            set1.setMode(LineDataSet.Mode.CUBIC_BEZIER);
            set1.setCubicIntensity(0.2f);
            set1.setDrawFilled(true);
            set1.setDrawCircles(false);
            set1.setLineWidth(1.8f);
            set1.setCircleRadius(4f);
            set1.setCircleColor(getResources().getColor(R.color.CEAD79));
            set1.setHighLightColor(Color.rgb(244, 117, 117));
            set1.setColor(getResources().getColor(R.color.CEAD79));
            set1.setFillColor(Color.rgb(120, 93, 52));
            set1.setFillAlpha(100);
            set1.setDrawHorizontalHighlightIndicator(false);
            set1.setFillFormatter(new IFillFormatter() {
                @Override
                public float getFillLinePosition(ILineDataSet dataSet, LineDataProvider dataProvider) {
                    return chart.getAxisLeft().getAxisMinimum();
                }
            });

            // create a data object with the data sets
            LineData data = new LineData(set1);
            data.setValueTextSize(9f);
            data.setDrawValues(false);

            // set data
            chart.setData(data);
        }
    }

    //饼图数据填充
    private void setData(PieChart chart, int count, float range) {
        ArrayList<PieEntry> entries = new ArrayList<>();

        // NOTE: The order of the entries when being added to the entries array determines their position around the center of
        // the chart.
        for (int i = 0; i < count; i++) {
            entries.add(new PieEntry((float) ((Math.random() * range) + range / 5)));
        }

        PieDataSet dataSet = new PieDataSet(entries, "Election Results");

        dataSet.setDrawIcons(false);

        dataSet.setSliceSpace(3f);
        dataSet.setIconsOffset(new MPPointF(0, 40));
        dataSet.setSelectionShift(5f);

        // add a lot of colors

        ArrayList<Integer> colors = new ArrayList<>();

        for (int c : ColorTemplate.VORDIPLOM_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.JOYFUL_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.COLORFUL_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.LIBERTY_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.PASTEL_COLORS)
            colors.add(c);

        colors.add(ColorTemplate.getHoloBlue());

        dataSet.setColors(colors);
        //dataSet.setSelectionShift(0f);

        PieData data = new PieData(dataSet);
        data.setValueFormatter(new PercentFormatter());
        data.setValueTextSize(11f);
        data.setValueTextColor(Color.WHITE);
        data.setDrawValues(false);
        chart.setData(data);

        // undo all highlights
        chart.highlightValues(null);

        chart.invalidate();
    }

    @Override
    public void onResume() {
        super.onResume();
        aCache = ACache.get(getActivity());
        a_login = (A_Login) aCache.getAsObject(Constant.LOGIN);
    }

    @Override
    public void getData() {
        getList();
        getyesIncome();
        totalInput();
        productOut();
        queryAccoutRecords();
    }

    public void getList() {
        RetrofitUtil.getInstance().create(NetApi.class, 0)
                .found(reqs[index]).enqueue(new NetCallback<Result<WakuangBean>>() {
            @Override
            public void onSuccess(Result<WakuangBean> result) {
                if (result.isSuccess()) {
                    wakuangbean = result.getData();
                    refview();

                }
            }

            @Override
            public void netLogin() {

            }

            @Override
            public void onError(String errorStr) {
                super.onError(errorStr);
                Log.w("lxl", errorStr);

            }

        });
    }

    public void getyesIncome() {
        RetrofitUtil.getInstance().create(NetApi.class, 0)
                .yesIncome(reqs[index]).enqueue(new NetCallback<Result<Double>>() {
            @Override
            public void onSuccess(Result<Double> result) {
                if (result.isSuccess()) {
                    tvyesday.setText("昨日收益 :" + result.getData() + reqs[index].toUpperCase());
                }
            }

            @Override
            public void netLogin() {

            }

            @Override
            public void onError(String errorStr) {
                super.onError(errorStr);
                Log.w("lxl", errorStr);

            }

        });
    }

    public void queryAccoutRecords() {
        RetrofitUtil.getInstance().create(NetApi.class, 0)
                .queryAccoutRecords(reqs[index],
                        "1",
                        0,
                        31,
                        new ArrayList<>())
                .enqueue(new NetCallback<Result<RecordBean>>() {
                    @Override
                    public void onSuccess(Result<RecordBean> result) {
                        setData(result.getData());
                    }

                    @Override
                    public void netLogin() {

                    }

                    @Override
                    public void onError(Result result) {
                        super.onError(result);
                    }
                });
    }


    public void totalInput() {
        RetrofitUtil.getInstance().create(NetApi.class, 0)
                .totalInput(reqs[index]).enqueue(new NetCallback<Result<Inbean>>() {
            @Override
            public void onSuccess(Result<Inbean> result) {
                if (result.isSuccess()) {
                    tvInRmb.setText(result.getData().getRmb() + "");
                    tvInUsdt.setText(result.getData().getUsdt() + "");
                    tvInBtc.setText(result.getData().getBtc() + "");
                    piechart1.setCenterText(generateCenterSpannableText("累计投入\n￥" + result.getData().getTotal()));
                }
            }

            @Override
            public void netLogin() {

            }

            @Override
            public void onError(String errorStr) {
                super.onError(errorStr);
                Log.w("lxl", errorStr);

            }

        });
    }

    public void productOut() {
        RetrofitUtil.getInstance().create(NetApi.class, 0)
                .productOut(reqs[index]).enqueue(new NetCallback<Result<OutBean>>() {
            @Override
            public void onSuccess(Result<OutBean> result) {
                if (result.isSuccess()) {
                    //产出productOut
                    //    //预计产出futureProductOut
                    //    //云矿机btcZeroType
                    //    //矿机btcOneType
                    tvOutsl.setText(result.getData().getBtcZeroType() + "");
                    tvOutkj.setText(result.getData().getBtcOneType() + "");
                    piechart2.setCenterText(generateCenterSpannableText("预计待产出\n￥" + result.getData().getFutureProductOut()));
                }
            }

            @Override
            public void netLogin() {

            }

            @Override
            public void onError(String errorStr) {
                super.onError(errorStr);
                Log.w("lxl", errorStr);

            }

        });
    }

    private void refview() {
        tvqwsl.setText(wakuangbean.getComputingPower());
        tvslnd.setText(wakuangbean.getMachinePower());
        tvdqbj.setText(wakuangbean.getPrice() + "");
        tvmtcc.setText(wakuangbean.getProductOut());

    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        aCache = ACache.get(getActivity());
        a_login = (A_Login) aCache.getAsObject(Constant.LOGIN);
    }


    /**
     * onDestroyView中进行解绑操作
     */
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {

    }


    @OnClick({R.id.ivJiSuan, R.id.tvCommit, R.id.tvRight, R.id.ivShow})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ivShow:
                showValue = !showValue;
                if (showValue) {
                    tvTotalcc.setText("0");
                    tvDcc.setText("0");
                    ivShow.setImageResource(R.mipmap.show);
                } else {
                    tvTotalcc.setText("***");
                    tvDcc.setText("***");
                    ivShow.setImageResource(R.mipmap.hide);
                }
                break;
            case R.id.tvRight:
                OptionsPickerView devtypepvOptions = new OptionsPickerBuilder(getActivity(), new OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int options2, int options3, View v) {
                        index = options1;
                        getList();
                        getyesIncome();
                        totalInput();
                        productOut();
                        queryAccoutRecords();
                    }
                })
                        .setTitleText("选择币种")
                        .setContentTextSize(20)//设置滚轮文字大小
                        .setDividerColor(Color.LTGRAY)//设置分割线的颜色
                        .setSelectOptions(0, 0)//默认选中项
                        .setBgColor(R.color.c1E1D1D)
                        .setTitleBgColor(getResources().getColor(R.color.c1E1D1D))
                        .setTitleColor(getResources().getColor(R.color.cffffff))
                        .setCancelColor(getResources().getColor(R.color.colorMain))
                        .setSubmitColor(getResources().getColor(R.color.colorMain))
                        .setTextColorCenter(Color.LTGRAY)
                        .isRestoreItem(true)//切换时是否还原，设置默认选中第一项。
                        .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
//                .setLabels("省", "市", "区")
                        .setOutSideColor(0x00000000) //设置外部遮罩颜色
                        .setOptionsSelectChangeListener(new OnOptionsSelectChangeListener() {
                            @Override
                            public void onOptionsSelectChanged(int options1, int options2, int options3) {
//                        String str = "options1: " + options1 + "\noptions2: " + options2 + "\noptions3: " + options3;
//                        Toast.makeText(LoginOrRegestActivity.this, str, Toast.LENGTH_SHORT).show();
                            }
                        })
                        .build();

                devtypepvOptions.setPicker(Arrays.asList(reqs));//一级选择器
                devtypepvOptions.show();
                break;
            case R.id.ivJiSuan:
                break;
            case R.id.tvCommit:
                startActivity(new Intent(getActivity(), ProductListActivity.class));
                break;
        }
    }


    @Override
    public void onValueSelected(Entry e, Highlight h) {

        if (e == null)
            return;
        Log.i("VAL SELECTED",
                "Value: " + e.getY() + ", index: " + h.getX()
                        + ", DataSet index: " + h.getDataSetIndex());
    }

    @Override
    public void onNothingSelected() {
        Log.i("PieChart", "nothing selected");
    }

}
